<template>
  <div ref="filterPanelRef" class="collapse-panel-wp filter-item ds-panel-filter">
    <div class="filter-panel-header flex justify_between align_center">
      <div class="panel-title">
        <div class="flex align_center">
          <!--   拖拽图标   -->
          <template v-if="draggable">
            <i
                class="iconfont icon-tuozhuai drag-btn"
                draggable="true"
                @dragstart="dragStart"
                @dragend="dragEnd"
            ></i>
            <n-checkbox v-model:checked="com.dataSource.source.useAutoUpdate" class="mr_6" size="small"></n-checkbox>
          </template>
          <!--   名称      -->
          <div class="filter-name">
            <n-input
                v-if="editing"
                v-model:value="dataFilter.name"
                :autofocus="true"
                size="small"
                class="filter-name-input"
                @blur="editName"
            />
            <div v-else class="filter-name-text" :title="dataFilter.name">
              {{ dataFilter.name }}
            </div>
          </div>
          <!--    修改图标  -->
          <div class="action-wp_edit">
            <n-popover trigger="hover">
              <template #trigger>
                <i class="iconfont icon-edit filter-btn" @click="editing = true"></i>
              </template>
              <span>重命名</span>
            </n-popover>
          </div>
          <!--   组件调用次数   -->
          <div class="filter-count">
            <template v-if="!isNew && usedFilters[dataFilter.id]">
              <n-tooltip placement="top" trigger="hover">
                <template #trigger>
                  <span>{{ usedFilters[dataFilter.id].names.length }} 个组件正在调用</span>
                </template>
                <div>{{ usedFilters[dataFilter.id].names.join(", ") }}</div>
              </n-tooltip>
            </template>
          </div>
          <!--  展示详情     -->
          <div class="action-wp_delete">
            <n-popover trigger="hover">
              <template #trigger>
                <i :class="`iconfont ${removable ?'icon-shanchu1':'icon-close'} filter-btn`"
                   @click="removeFilter(dataFilter.id)"></i>
              </template>
              <span>删除</span>
            </n-popover>
          </div>
          <template v-if="hasFeedback">
            <template v-if="errMsg">
              <n-tooltip placement="top" trigger="hover">
                <template #trigger>
                  <div class="filter-dot"></div>
                </template>
                <div>{{ errMsg }}</div>
              </n-tooltip>
            </template>
            <div v-else class="filter-dot"></div>
          </template>
          <div v-else class="filter-dot --none"></div>
        </div>
      </div>
      <div class="toggle-btn cursor_point px_6" @click="toggleEditor">
        <i :class="`iconfont ${collapse ? 'icon-xiala':'icon-right'}`"></i>
      </div>
    </div>
    <template v-if="isOpened">
      <n-collapse-transition :collapsed="collapse">
        <div class="panel-content-wp">
          <div class="cp-wrap">
            <p title="function filter(data) {" class="fake-code mt_0">
              <span class="--keyword">function</span> filter(data) {
            </p>
            <my-monaco-editor
                language="javascript"
                :code="code"
                :height="180"
                editor-class="filter-editor"
                @change="changeCode"
                @blur="updateCode"
            />
            <p class="fake-code mt_0">}</p>
            <div class="flex justify_between align_center p_4">
              <div v-if="isEdited" class="unsaved">未保存</div>
              <div v-else-if="showTime" class="saved fontsize_12">上次保存: {{ dataFilter.updateAt }}</div>
              <div class="filter-actions">
                <n-button
                    type="primary"
                    size="small"
                    class="base-primary-btn mx_4"
                    :loading="loading"
                    @click="saveData">
                  {{
                    dataFilter.id === "0" ? "保存" : isEdited ? "保存" : "完成"
                  }}
                </n-button>
                <n-button size="small" class="bolder-btn" @click="cancelEdit">
                  {{
                    dataFilter.id === "0" ? "取消" : isEdited ? "撤销" : "取消"
                  }}
                </n-button>
              </div>
            </div>
          </div>
        </div>
      </n-collapse-transition>
    </template>
  </div>
</template>

<script>
import { defineComponent, inject, ref } from "vue";
import { ElMessage } from "element-plus";
// import { NButton, NCheckbox, NCollapseTransition, NInput, NPopover, NTooltip, useMessage } from "naive-ui";

export default defineComponent({
  name: "filter-collapse-panel",
  props: {
    draggable: {
      type: Boolean,
      default: true,
    },
    isNew: {
      type: Boolean,
    },
    removable: {
      type: Boolean,
      default: true,
    },
    dataFilter: {
      type: Object,
      required: true
    },
    showTime: {
      type: String,
      default: "",
    }
  },
  components: {
    // NInput, NTooltip, NPopover, NCheckbox, NCollapseTransition, NButton
  },
  setup(props) {
    const com = inject("com");
    const editing = ref(props.isNew);
    const usedFilters = inject("usedFilters");
    const saveFilter = inject("saveFilter");
    const removeFilter = inject("removeFilter");
    const hasFeedback = ref(false);
    const errMsg = ref("");
    const isOpened = ref(props.isNew);
    const collapse = ref(props.isNew);
    const isEdited = ref(props.isNew);
    const code = ref(props.dataFilter.origin);
    const editFilterName = inject("editFilterName");
    const loading = ref(false);
    const dragStart = () => {

    };
    const dragEnd = () => {

    };
    const toggleEditor = () => {
      isOpened.value = true;
      collapse.value = !collapse.value;
    };
    const changeCode = () => {
      console.log(code.value);
      console.log(props.dataFilter.origin);
      if (code.value != props.dataFilter.origin) {
        isEdited.value = true;
      }
    };
    const updateCode = (data) => {
      code.value = data.value;
    };
    const cancelEdit = () => {
      if (props.isNew) {
        removeFilter("0");
      } else {
        code.value = props.dataFilter.origin;
        if (isEdited.value) {
          isEdited.value = false;
        } else {
          collapse.value = false;
        }
      }
    };
    const editName = () => {
      editing.value = false;
      editFilterName(props.dataFilter.name, props.dataFilter);
    };
    const saveData = async () => {
      if (!isEdited.value) {
        collapse.value = false;
        return;
      }
      try {
        loading.value = true;
        props.dataFilter.origin = code.value;
        console.log(code.value);
        props.dataFilter.code = `
          if (!data) {  return data; }
          return filter(...arguments);
          function filter(data) {
            ${code.value}
            return data;
          }
        `;
        await saveFilter(props.dataFilter);
        isEdited.value = false;
        ElMessage({
          type: "success",
          message: "数据过滤器已保存",
        });
      } catch (error) {
        loading.value = false;
        ElMessage.error(error.message);
      } finally {
        loading.value = false;
      }
    };
    return {
      com,
      usedFilters,
      errMsg,
      hasFeedback,
      editing,
      isOpened,
      collapse,
      isEdited,
      code,
      editFilterName,
      loading,
      editName,
      dragStart,
      dragEnd,
      toggleEditor,
      changeCode,
      updateCode,
      cancelEdit,
      saveData,
      removeFilter
    };
  }
});
</script>

<style lang="less" scoped>
.filter-item {
  margin: 0 0 10px 0;
  box-shadow: 0 0 10px -3px #000;
  transition: opacity .2s;

  .filter-panel-header {
    padding-left: 2px;
    display: flex;
    height: 30px;
    line-height: 30px;
    align-items: center;
    position: relative;
    border: 1px solid #566273;
    color: #bcc9d4;
    background: #262c33;
    transition: border-color .2s;

    .panel-title {
      flex: 1;

      .drag-btn {
        display: block;
        height: 30px;
        width: 16px;
        text-align: center;
        cursor: move;
      }

      .filter-name {
        position: relative;
        width: 100px;

        :deep(.n-input) {
          width: 100px;

          input {
            width: 100px;
            height: 12px;
            font-size: 12px;
          }
        }
      }

      .action-wp_edit {
        width: 40px;
        text-align: center;

        .icon-edit {
          width: 40px;
          cursor: pointer;
        }
      }

      .filter-btn {
        opacity: 0;
        cursor: pointer;
        pointer-events: none;
        transition: .1s;
      }

      .filter-count {
        flex: 1;
      }

      .action-wp_delete {
        width: 30px;
        text-align: center;
        padding: 0 5px;
      }
    }

    .toggle-btn {
      border-left: 1px solid #566273;
    }

    &:hover {
      .filter-btn {
        opacity: 1;
        pointer-events: auto;
      }
    }
  }

  .fake-code {
    font-family: Menlo-Regular, monospace;
    color: #ccc;
    padding-left: 8px;
    height: 28px;
    line-height: 28px;
    background: #0e1013;
    margin-bottom: 0;
    user-select: none;
  }

  .cp-wrap {
    :deep(.filter-editor) {
      padding: 0;
      border: 0;
    }
  }

  .filter-count {
    font-size: 12px;
  }
}
</style>